#include "concretestate.h"

Host::Host()
{
    currentStatePtr = std::make_shared<std::shared_ptr<AbstractState>>();
    *currentStatePtr = std::make_shared<State1>(currentStatePtr);
}

int Host::update()
{
    return (*currentStatePtr)->update();
}

void Host::check_timeout()
{
    return (*currentStatePtr)->check_timeout();
}

bool Host::is_end()
{
    return (*currentStatePtr)->is_end();
}

///////////////////////////////////////////////////////////////

void HostPool::check_timeout()
{
    std::unique_lock locker(mtx);
    for (auto it = pool.begin(); it != pool.end(); ++it)
    {
        (*it->second).check_timeout();
    }
}

void HostPool::clean()
{
    std::unique_lock locker(mtx);
    for (auto it = pool.begin(); it != pool.end();)
    {
        if ((*it->second).is_end()) {
            it = pool.erase(it);
        }
        else {
            ++it;
        }
    }
}

int HostPool::size()
{
    std::unique_lock locker(mtx);
    return pool.size();
}

std::shared_ptr<Host> HostPool::instance(const std::string &id)
{
    std::unique_lock locker(mtx);
    std::shared_ptr<Host> ptr = pool[id];
    if(!ptr) {
        ptr = std::make_shared<Host>();
        pool[id] = ptr;
    }
    return ptr;
}

